/**
 * Created by liubin on 2017/2/23.
 */


var WhmjTableStatus = function () {
    var that = new WhmjTableMsgStatus();

    //牌桌映像
    that.mTableStatus = null;

    //牌桌结算印象
    that.mTableResults = [];


    //设置牌桌映像
    that.setTableStatus = function(tableStatus){
        that.mTableStatus = tableStatus;

        //在武汉麻将里面才触发
        if (mo.sceneHelper.currentLayerName != "whmj"){
            return;
        }

        that.updateTableStatus();
    };


    //断线重连
    that.setReconnectStatus = function (tableStatus) {
        that.mTableStatus = tableStatus;

        //过滤
        if (that.filterErrorMsg()){
            return;
        }

        //重置
        that.mTableCardCount = null;

        //更新用户信息
        that.updateUserInfo();

        //设置当前操作玩家
        that.setCurrentPlayer();

        //显示当前开口
        that.setOpenCardType();

        //显示自己的吃碰杠胡操作
        that.setTableOperating();

        //牌桌重绘
        mo.whmjTabel.mWhmjCardLayer.setReconnectStatus(tableStatus);

        //更新牌桌step
        mo.whmjTabel.updateTableStep(that.mTableStatus.Step);

    };

    //更新牌桌映象
    that.updateTableStatus = function(){

        //过滤
        if (that.filterErrorMsg()){
            return;
        }

        //重置
        that.mTableCardCount = null;

        //更新用户信息
        that.updateUserInfo();

        //设置当前操作玩家
        that.setCurrentPlayer();

        //显示当前开口
        that.setOpenCardType();

        //显示自己的吃碰杠胡操作
        that.setTableOperating();

        //更新牌局信息
        that.updateStep();

        //更新牌桌step
        mo.whmjTabel.updateTableStep(that.mTableStatus.Step);

        //播放音效
        that.playMusic();

    };

    //过滤会让游戏错误的信息
    that.filterErrorMsg = function(){
        var isError = false;
        //退桌之前受到 seatUser为null
        if (that.mTableStatus.Step == 2){
            var isNull = false;
            for (var i = 1; i <=4; i++){
                if (that.mTableStatus["SeatUser" + i] == null){
                    isNull = true;
                    break;
                }
            }
            if (isNull){
                isError = true;
            }
        }

        return isError;
    };

    //更新用户信息
    that.updateUserInfo = function(){
        if (that.mTableStatus.TableID){
            var seatUser = [that.mTableStatus.SeatUser1, that.mTableStatus.SeatUser2, that.mTableStatus.SeatUser3, that.mTableStatus.SeatUser4];
            var infos = [null, null, null, null];
            for (var i = 0; i < 4; i++){
                infos[that.getViewForLogic(i, that.mTableStatus.MySeat - 1)] = seatUser[i];
                if (seatUser[i] != null){
                    infos[that.getViewForLogic(i, that.mTableStatus.MySeat - 1)].Score = (seatUser[i].Score != null) ? seatUser[i].Score : 0;
                }
            }
            mo.whmjTabel.mWhmjUILayer.setUserInfos(infos);
        }else{
            //录像可能没有
        }
    };

    //设置当前操作玩家
    that.setCurrentPlayer = function(){
        var seat = 0;
        var timeleft = (that.mTableStatus.NextActionTimeOut != null ? that.mTableStatus.NextActionTimeOut : 10);

        var NowSeat = that.mTableStatus.NowSeat;
        if (NowSeat.length == 0){
            seat = -1;
        }else if (NowSeat.length == 1){
            seat = that.getViewForLogic(NowSeat[0] - 1, that.mTableStatus.MySeat - 1);
        }else{
            seat = -1;
        }

        mo.whmjTabel.setCurrentPlayer(seat);
    };


    //更新牌局信息
    that.updateStep = function(){
        if (that.mTableStatus.Step == 0){ //非打牌阶段

        }else if (that.mTableStatus.Step == 1){ //打牌阶段
            //是否起牌
            var isQipai = false;
            if(!that.mTableStatus.LastAction){
                isQipai = true;
            }

            if(isQipai){
                //发牌
                var cardss = [[], [], [], []];
                for (var i = 0; i < 4; i++){
                    var seatUser = that.getTableUserStatswhmj(i);
                    var cards = [];
                    if (seatUser){
                        cards = seatUser.HandCards;
                        if (cards.length == 0){
                            for (var j = 0; j < seatUser.LeftCards; j++){
                                cards.push(0);
                            }
                        }
                    }
                    cardss[i] = cards;
                }
                mo.soundHelper.playStartGame();

                var laizi = that.mTableStatus.LZ;
                var singCards = that.mTableStatus.SG;
                singCards.push(laizi);
                mo.whmjTabel.setInhandCards(cardss, laizi, singCards);
                return;
            }

            //判断在做什么
            var LastAction = that.mTableStatus.LastAction;
            var LastActionSeat = that.mTableStatus.LastActionSeat - 1;
            LastActionSeat = that.getViewForLogic(LastActionSeat, that.mTableStatus.MySeat - 1);

            var NowSeat = that.mTableStatus.NowSeat - 1;
            NowSeat = that.getViewForLogic(NowSeat, that.mTableStatus.MySeat - 1);

            if (LastAction.code == 8){
                //出牌
                var dealCard = LastAction.Cards1[0];
                var DrawCard = that.mTableStatus.DrawCard;

                mo.whmjTabel.setDealCard(LastActionSeat, dealCard);

                if (that.mTableStatus.IsPlayCard){
                    mo.whmjTabel.addInhandCard(NowSeat, DrawCard);
                }

                //提示玩家打出的牌
                var showDealCard = [0, 0, 0, 0];
                showDealCard[LastActionSeat] = dealCard;
                mo.whmjTabel.mWhmjUILayer.mWhmjTableResultLayer.showDealCard(showDealCard);
            }else if (LastAction.code == 1){
                //吃
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[1]];
                var openType = 1;

                mo.whmjTabel.setOpenCard(LastActionSeat, cardNums, openType);
            }else if (LastAction.code == 2){
                //碰
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0]];
                var openType = 2;

                mo.whmjTabel.setOpenCard(LastActionSeat, cardNums, openType);
            }else if (LastAction.code == 3){
                //胡
                mo.whmjTabel.onPlayTableOpAnim();

            }else if (LastAction.code == 4){
                //明杠
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0]];
                var openType = 4;
                var DrawCard = that.mTableStatus.DrawCard;

                mo.whmjTabel.setOpenCard(LastActionSeat, cardNums, openType);
                mo.whmjTabel.addInhandCard(NowSeat, DrawCard);
            }else if (LastAction.code == 5){
                //暗杠
                var cardNums = [LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0], LastAction.Cards1[0]];
                var openType = 5;
                var DrawCard = that.mTableStatus.DrawCard;

                mo.whmjTabel.setOpenCard(LastActionSeat, cardNums, openType);
                mo.whmjTabel.addInhandCard(NowSeat, DrawCard);

            }else if (LastAction.code == 6){
                //补杠
                var cardNums = [LastAction.Cards1[0]];
                var openType = 6;
                var DrawCard = that.mTableStatus.DrawCard;

                mo.whmjTabel.setOpenCard(LastActionSeat, cardNums, openType);

                if (LastActionSeat == NowSeat){
                    //不一致说明 有人通过补杠胡牌了
                    mo.whmjTabel.addInhandCard(NowSeat, DrawCard);
                }

            }else if (LastAction.code == 7){
                //单杠
                var singNum = [LastAction.Cards1[0]];
                var openType = 7;
                mo.whmjTabel.setOpenCard(LastActionSeat, singNum, openType);

                //添加手牌
                var DrawCard = that.mTableStatus.DrawCard;
                if (that.mTableStatus.IsPlayCard){
                    mo.whmjTabel.addInhandCard(NowSeat, DrawCard);
                }
            }else if (LastAction.code == 9){
                //过
                var DrawCard = that.mTableStatus.DrawCard;

                if (that.mTableStatus.IsPlayCard){
                    mo.whmjTabel.addInhandCard(NowSeat, DrawCard);
                }
            }

            that.checkTableDisplay();

        }
    };

    //检测显示数据和录像是否一直 不一致刷新整个牌桌
    that.checkTableDisplay = function(){
        if (that.mTableStatus.Step == 2){

            var isUnanimous = true;
            for (var seat = 0; seat < 3; seat++){
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                //服务端数据
                var seatUser = that.mTableStatus["SeatUser" + (logicSeat + 1)];
                //本地显示数据
                var player = mo.whmjTabel.mWhmjCardLayer.mPlayers[seat];

                if (seatUser != null){
                    //检测手牌
                    if (player.inhandCards.length != seatUser.LeftCards){
                        isUnanimous = false;
                        break;
                    }

                    //检测打出牌
                    if (player.dealCards.length != seatUser.PlayCards.length){
                        isUnanimous = false;
                        break;
                    }

                    //检测开口牌
                    if (player.openCards.length != seatUser.Groups.length){
                        isUnanimous = false;
                        break;
                    }
                }
            }

            if (!isUnanimous){
                cc.log("检测到不一致了 开始重绘手牌了");
                mo.whmjTabel.resetTable();
                mo.whmjTabel.mWhmjCardLayer.setReconnectStatus(that.mTableStatus);
            }
        }
    };


    that.setOpenCardType = function(){
        if (that.mTableStatus.Step != 1){
            return;
        }
        var LastAction = that.mTableStatus.LastAction;
        if (LastAction){
            var types = [-1, -1, -1, -1];
            var LastActionSeat = that.mTableStatus.LastActionSeat - 1;
            LastActionSeat = that.getViewForLogic(LastActionSeat, that.mTableStatus.MySeat - 1);

            if (LastAction.code == 1 ||
                LastAction.code == 2 ||
                LastAction.code == 3 ||
                LastAction.code == 4 ||
                LastAction.code == 5 ||
                LastAction.code == 6 ||
                LastAction.code == 7
            ){
                types[LastActionSeat] = LastAction.code;
                if (LastAction.code == 3){
                    //找到自摸的情况 为33
                    var isZimo = false;
                    if (LastAction.Cards2.length > 0){
                        isZimo = LastAction.Cards2[LastAction.Cards2.length - 1] == 0;
                    }
                    types[LastActionSeat] = isZimo ? 33 : 3;
                }
                mo.whmjTabel.mWhmjUILayer.mWhmjTableResultLayer.showResult(types);
            }
        }
    };

    that.setTableOperating = function () {
        var myUseActionRequest = [];
        var isMyOperating = false;

        for(var i = 0; i < that.mTableStatus.NowSeat.length; i++){
            if (that.mTableStatus.NowSeat[i] == that.mTableStatus.MySeat){
                isMyOperating = true;
                break;
            }
        }

        if (isMyOperating){
            //可以碰杠,单杠不处理
            var seatUser = that.getTableUserStatswhmj(0);
            for (var i = 0; i < seatUser.NewActionList.length; i++){
                var ActionRequestwhmjItem = seatUser.NewActionList[i];
                var code = ActionRequestwhmjItem.code;
                if (code == 1 || code == 2 || code == 3 || code == 4 || code == 5 || code == 6 || code == 9){
                    myUseActionRequest.push(ActionRequestwhmjItem);
                }
            }
            if (myUseActionRequest.length == 0){
                isMyOperating = false;
            }
        }

        //通知ui
        mo.whmjTabel.mWhmjUILayer.mWhmjControlLayer.showOperating(isMyOperating, myUseActionRequest);
    };

    //设置录像
    that.setReplayMsg = function(rePlaywhmj){
        that.replayMsgs = [];
        that.replayTypes = [];

        //设置录像时候自己的座位号
        var replayMySeat = 1;
        for(var i = 1; i <= 4; i++){
            var roundEndedEventwhmj = rePlaywhmj.Result;
            if (roundEndedEventwhmj["SeatUser" + i] != null){
                if (roundEndedEventwhmj["SeatUser" + i].user_info != null){
                    if (roundEndedEventwhmj["SeatUser" + i].user_info.userid == mo.gameUserInfo.uid){
                        replayMySeat = i;
                        roundEndedEventwhmj.MySeat = replayMySeat;
                        break;
                    }
                }
            }
        }

        //排序用的结构体
        var msgStruct = [];

        //牌桌映像数据
        for (var i = 0; i < rePlaywhmj.Images.length; i++){
            var tableStatswhmj = rePlaywhmj.Images[i];
            //修改MySeat
            tableStatswhmj.MySeat = replayMySeat;

            var msgid = 2006;

            var msgItem = {};
            msgItem.key = msgid;
            msgItem.msg = tableStatswhmj;
            msgStruct.push(msgItem);
        }

        //货币结算数据
        for (var i = 0; i < rePlaywhmj.Result.RunTimeResult.length; i++){
            var tableStatswhmj = rePlaywhmj.Result.RunTimeResult[i];
            var msgid = 2017;

            var msgItem = {};
            msgItem.key = msgid;
            msgItem.msg = tableStatswhmj;
            msgStruct.push(msgItem);
        }

        msgStruct.sort(function(a, b){
            return a.msg.PkgIndex - b.msg.PkgIndex;
        });

        for (var i = 0; i < msgStruct.length; i++){
            that.replayMsgs.push(msgStruct[i].msg);
            that.replayTypes.push(msgStruct[i].key);
        }

        //牌桌结算数据
        that.replayMsgs.push(rePlaywhmj.Result);
        that.replayTypes.push(2008);
    };

    //播放录像
    that.playReplay = function(){
        if (that.replayMsgs.length > 0){
            var msg = that.replayMsgs.shift();
            var type = that.replayTypes.shift();

            var response = null;
            if (type == 2006){
                //牌桌映象
                response = new WhmjTableStatswhmj();

            }else if (type == 2008){
                //牌桌结算
                response = new WhmjRoundEndedEventwhmj();

            }else if (type == 2017){
                //牌桌小结算
                response = new WhmjTableRunTimeResultwhmj();
            }

            if (response){
                response.handleMsg(msg);
                response.log();
            }else{
                cc.warn("type:" + type + "未注册");
            }

            // if (that.replayTypes.length > 0){
            //     //小结算在杠牌的前面
            //     if (type == 1417){
            //
            //         if (that.replayTypes[0] != 1417){
            //             //当前是小结算 下次不是小结算 就显示结算
            //             that.handlerTableResult();
            //         }
            //
            //         return that.playReplay();
            //     }else if(that.replayTypes[0] == 1406 && that.replayMsgs[0].Step == 1){
            //         return that.playReplay();
            //     }
            // }

            return true;
        }else{
            cc.log("录像播放完毕");
            return false;
        }

    };


    //返回TableUserStatswhmj
    that.getTableUserStatswhmj = function(viewSeat){
        var seatUsers = [that.mTableStatus.SeatUser1, that.mTableStatus.SeatUser2, that.mTableStatus.SeatUser3, that.mTableStatus.SeatUser4];
        var logicSeat = that.getLogicForView(viewSeat, that.mTableStatus.MySeat - 1);

        return seatUsers[logicSeat];
    };


    that.getLogicForView = function(view, myLogicSeat){
        var logic = (view + 4 + myLogicSeat) % 4;
        return logic;
    };

    that.getViewForLogic = function(logic, myLogicSeat){
        var view = (logic + 4 - myLogicSeat) % 4;
        return view;
    };


    //通过ui的返回玩家视图座位号
    that.getViewSeatForUid = function (uid) {
        var logicIndex = -1;
        for (var i = 0; i < 4; i++){
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser != null){
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid){
                    logicIndex = i;
                }
            }
        }
        if (logicIndex != -1){
            return that.getViewForLogic(logicIndex, that.mTableStatus.MySeat - 1);
        }else{
            return -1;
        }
    };


    //通过用户id获取用户性别
    that.getSexForUid = function(uid){
        var sex = 0;
        for (var i = 0; i < 4; i++){
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser != null && seatUser.user_info != null){
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid){
                    sex = seatUser.user_info.sex;
                }
            }
        }
        return sex;
    };

    that.getEatGroups = function () {
        var eatGroups = [];

        //上个玩家的操作
        var LastAction = that.mTableStatus.LastAction;

        if (LastAction.code == 8){
            //上个玩家打的牌
            var dealCard = LastAction.Cards1[0];
            //我手中的牌
            var myHandCards = that.getTableUserStatswhmj(0).HandCards;

            for (var i = dealCard - 2; i <= dealCard; i++){
                var group = [];
                for (var j = i; j <= i + 2; j++){
                    if(j == dealCard){
                        continue;
                    }
                    for (var z=0; z<myHandCards.length; z++){
                        if(j == myHandCards[z]){
                            group.push(j);
                            break;
                        }
                    }
                }
                if(group.length == 2){
                    eatGroups.push(group);
                }
            }
        }

        return eatGroups;
    };

    //处理货币结算
    that.getTableResultScores = function(){
        var scores = [0, 0, 0, 0];
        if (that.mTableResults.length != 0){
            for (var i = 0; i < that.mTableResults.length; i++){
                var item = that.mTableResults[i];
                if (item.ResultType == 4){
                    var addSeat = that.getViewForLogic(item.ToSeat - 1, that.mTableStatus.MySeat - 1);
                    var subSeat = that.getViewForLogic(item.FromSeat - 1, that.mTableStatus.MySeat - 1);
                    var score = item.PayMoney;
                    scores[addSeat] += score;
                    scores[subSeat] -= score;
                }
            }
            that.mTableResults.splice(0, that.mTableResults.length);
        }
        return scores;
    };


    //播放音效
    that.playMusic = function(){
        var LastAction = that.mTableStatus.LastAction;
        if (LastAction == null){
            return;
        }
        var sex = 0;
        if (that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat] != null && that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].user_info != null){
            sex = that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].user_info.sex;
        }

        if (that.mTableStatus.Step == 1){
            if (LastAction.code == 8){
                //出牌
                mo.soundHelper.playMjDeal();

                var dealCard = LastAction.Cards1[0];
                mo.soundHelper.playMjCardWhmj(dealCard, sex);

            }else if (LastAction.code == 1){
                //吃
                mo.soundHelper.playMjPengEffect();

                mo.soundHelper.playMjChiWhmj(sex);

            }else if (LastAction.code == 2){
                //碰
                mo.soundHelper.playMjPengEffect();

                mo.soundHelper.playMjPengWhmj(sex);
            }else if (LastAction.code == 4){
                //明杠
                mo.soundHelper.playMjPengEffect();

                var cardNum = [LastAction.Cards1[0]];
                mo.soundHelper.playMjGangWhmj(sex, 4, cardNum);
            }else if (LastAction.code == 5){
                //暗杠
                mo.soundHelper.playMjPengEffect();

                var cardNum = [LastAction.Cards1[0]];
                mo.soundHelper.playMjGangWhmj(sex, 5, cardNum);
            }else if (LastAction.code == 6){
                //补杠
                mo.soundHelper.playMjPengEffect();

                var cardNum = [LastAction.Cards1[0]];
                mo.soundHelper.playMjGangWhmj(sex, 6, cardNum);
            }else if (LastAction.code == 7){
                //单杠
                mo.soundHelper.playMjPengEffect();

                var cardNum = [LastAction.Cards1[0]];
                mo.soundHelper.playMjGangWhmj(sex, 7, cardNum);
            }else if (LastAction.code == 9){
                //过
            }else if (LastAction.code == 3){
                //胡
                var isZimo = false;
                if (LastAction.Cards2.length > 0){
                    isZimo = LastAction.Cards2[LastAction.Cards2.length - 1] == 0;
                }
                if (false){
                    if (isZimo){
                        mo.soundHelper.playMjZimo(sex);
                    }else{
                        mo.soundHelper.playMjHu(sex);
                    }
                }
            }
        }
    };


    return that;
};

mo.whmjTableStatus = new WhmjTableStatus();
